﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Cnblogs.Service;
using System.Collections.ObjectModel;
using Alexis.WindowsPhone;
using Microsoft.Phone.Shell;

namespace Cnblogs
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            lbx_home.ItemsSource = (App.Current as App).HomeItems;
            lbx_recent.ItemsSource = (App.Current as App).RecentItems;
            lbx_recommend.ItemsSource = (App.Current as App).RecommendItems;
            lbx_hot.ItemsSource = (App.Current as App).HotItems;
        }

        private int _homePage = 1;
        private int _recommendPage = 1;
        private int _hotPage = 1;
        private int _recentPage = 1;
        private bool _isLocked = false;

        private bool _isRequestingHome = false;
        private bool _isRequestingRecent = false;
        private bool _isRequestingRecommend = false;
        private bool _isRequestingHot = false;

        #region page event
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }
        #endregion
        

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (pivot.SelectedIndex != -1)
            {
                App.PivotIndex = pivot.SelectedIndex;
            }
            switch (pivot.SelectedIndex)
            {
                case 0:
                    if ((App.Current as App).HomeItems.Count == 0)
                    {
                        loadHome(false, true);
                    }
                    break;
                case 1:
                    if ((App.Current as App).RecentItems.Count == 0)
                    {
                        loadRecent(false, true);
                    }
                    break;
                case 2:
                    if ((App.Current as App).RecommendItems.Count == 0)
                    {
                        loadRecommend(false, true);
                    }
                    break;
                case 3:
                    if ((App.Current as App).HotItems.Count == 0)
                    {
                        loadHot(false, true);
                    }
                    break;
                default:
                    break;
            }
        }

        private void resetIsRequesting(ServiceType type)
        {
            if (type == ServiceType.Home)
            {
                _isRequestingHome = false;
            }
            else if (type== ServiceType.Hot)
            {
                _isRequestingHot = false;
            }
            else if (type== ServiceType.Recent)
            {
                _isRequestingRecent = false;
            }
            else if (type== ServiceType.Recommend)
            {
                _isRequestingRecommend = false;
            }
        }

        private void requestData(ObservableCollection<Entry> entry, ServiceType type, NewsData data, bool isRefresh, bool isLoadCache)
        {
            GlobalIndicator.Instance.StartBusy(Constants.L_GettingData);

            #region load cache
            if (isLoadCache)
            {
                var feed = CacheService.loadCache(type) as NewsFeed;

                if (feed != null && feed.Items != null && feed.Items.Length > 0)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        for (int i = 0; i < feed.Items.Length; i++)
                        {
                            entry.Add(feed.Items[i]);
                        }
                    });
                }
            }
            #endregion
            
            FeedService.Request(type, data, (obj, isSuccess) =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    GlobalIndicator.Instance.StopBusy();
                    resetIsRequesting(type);
                    if (isSuccess)
                    {
                        if (isRefresh)
                        {
                            entry.Clear();
                        }
                        if (entry.Count>0)
                        {
                            entry.Last().LoadMoreVisibility = Visibility.Collapsed;
                        }
                        var feeds = obj as NewsFeed;
                        if (feeds!=null && feeds.Items!=null)
                        {
                            feeds.Items.Last().LoadMoreVisibility = Visibility.Visible;
                            int i = 0;
                            if (type == ServiceType.Hot)
                            {
                                i = (data.PageIndex - 1) * GlobalFunc.PageSize;
                            }
                            if (isRefresh)
                            {
                                CacheService.saveCache(type, feeds);  
                            }
                            for (i = 0; i < feeds.Items.Length; i++)
                            {
                                var en = entry.FirstOrDefault(x => x.Id == feeds.Items[i].Id);
                                if (en==null)
                                {
                                    entry.Add(feeds.Items[i]);    
                                }                                
                            }
                        }                      
                    }
                    else
                    {
                        MessageBox.Show(Constants.L_NoInternetAccess);
                    }
                });
            });
        }

        private void menu_setting_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(Constants.P_SettingPage, UriKind.Relative));
        }

        private void menu_about_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(Constants.P_AboutPage, UriKind.Relative));
        }

        private void SelectItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var grd = sender as Grid;
            if (grd != null)
            {
                var entry = grd.DataContext as Entry;
                if (entry != null)
                {
                    (App.Current as App).CurrentEntry = entry;
                    NavigationService.Navigate(new Uri(Constants.P_NewsBodyPage, UriKind.Relative));
                }
            }
        }

        private void HomeFeed_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var grd = sender as Grid;
            if (grd != null)
            {
                var entry = grd.DataContext as Entry;
                if (entry != null)
                {
                    (App.Current as App).CurrentEntry = entry;
                    if ((App.Current as App).PostItems != (App.Current as App).HomeItems)
                    {
                        (App.Current as App).PostItems = (App.Current as App).HomeItems;
                    }
                    NavigationService.Navigate(new Uri(Constants.P_PostBodyPage, UriKind.Relative));
                }
            }
        }

        private void imgAvatar_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var img = sender as Image;
            if (img != null)
            {
                var entry = img.DataContext as Entry;
                if (entry != null)
                {
                    NavigationService.Navigate(new Uri(Constants.P_BloggerPage + "?blogapp=" + entry.BlogApp + "&name=" + entry.AuthorInfo.Name, UriKind.Relative));
                }
            }
        }

        private void btn_loadmore_click(object sender, RoutedEventArgs e)
        {
            if (pivot.SelectedIndex == 0)
            {
                _homePage++;
                loadHome();
            }
            else if (pivot.SelectedIndex == 1)
            {
                _recentPage++;
                loadRecent();
            }
            else if (pivot.SelectedIndex == 2)
            {
                _recommendPage++;
                loadRecommend();
            }
            else
            {
                _hotPage++;
                loadHot();
            }
        }

        #region load data
        private void loadHome(bool isRefresh = false, bool isLoadCache = false)
        {
            if (_isRequestingHome) return;
            _isRequestingHome = true;

            requestData((App.Current as App).HomeItems, ServiceType.Home, new NewsData()
            {
                PageIndex = _homePage,
                PageSize = GlobalFunc.PageSize
            }, isRefresh, isLoadCache);
        }

        private void loadRecent(bool isRefresh = false, bool isLoadCache = false)
        {
            if (_isRequestingRecent) return;
            _isRequestingRecent = true;

            requestData((App.Current as App).RecentItems, ServiceType.Recent, new NewsData()
            {
                PageIndex = _recentPage,
                PageSize = GlobalFunc.PageSize
            }, isRefresh, isLoadCache);
        }

        private void loadRecommend(bool isRefresh = false, bool isLoadCache = false)
        {
            if (_isRequestingRecommend) return;
            _isRequestingRecommend = true;

            requestData((App.Current as App).RecommendItems, ServiceType.Recommend, new NewsData
            {
                PageIndex = _recommendPage,
                PageSize = GlobalFunc.PageSize
            }, isRefresh, isLoadCache);
        }

        private void loadHot(bool isRefresh = false, bool isLoadCache = false)
        {
            if (_isRequestingHot) return;
            _isRequestingHot = true;

            requestData((App.Current as App).HotItems, ServiceType.Hot, new NewsData
            {
                PageIndex = _hotPage,
                PageSize = _hotPage * GlobalFunc.PageSize
            }, isRefresh, isLoadCache);
        }
        #endregion
        

        #region Appbar Event
        private void Appbar_Refresh_Click(object sender, EventArgs e)
        {
            if (pivot.SelectedIndex == 0)
            {
                _homePage = 1;
                loadHome(true);
            }
            else if (pivot.SelectedIndex == 1)
            {
                _recentPage = 1;
                loadRecent(true);
            }
            else if (pivot.SelectedIndex == 2)
            {
                _recommendPage = 1;
                loadRecommend(true);
            }
            else
            {
                _hotPage = 1;
                loadHot(true);
            }
        }

        private void Appbar_Review_Click(object sender, EventArgs e)
        {
            GlobalFunc.OpenReview();
        }

        private void Appbar_Lock_Click(object sender, EventArgs e)
        {
            _isLocked = !_isLocked;
            pivot.IsLocked = _isLocked;
            var button = base.ApplicationBar.Buttons[3] as ApplicationBarIconButton;
            if (button != null)
            {
                button.Text = pivot.IsLocked ? "解除锁定" : "锁定";
                button.IconUri = pivot.IsLocked ? new Uri("/Images/appbar_unlock.png", UriKind.Relative) : new Uri("/Images/appbar_lock.png", UriKind.Relative);
            }
        }

        private void Appbar_Search_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(Constants.P_SearchPage, UriKind.Relative));
        }
        #endregion
    }
}